/****************************************************
	文件：Helper.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2020/7/11 17:12:50
	功能：帮助方法
*****************************************************/

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;

namespace HTSpider
{
    public class Helper
    {
        public static string GetNowTimeStr()
        {
            return string.Concat(DateTime.Now.Year, "/", DateTime.Now.Month, "/", DateTime.Now.Day, " ", DateTime.Now.Hour, ":", DateTime.Now.Minute, ":", DateTime.Now.Second);
        }
        /// <summary>
        /// 新建文件夹
        /// </summary>
        public static void CreateDirectory(string folderFullPath)
        {
            if (Directory.Exists(folderFullPath) == false)
            {
                Directory.CreateDirectory(folderFullPath);
                Logger.LogFormat("创建文件夹，文件夹路径：\n{0}", folderFullPath);
            }
        }
        /// <summary>
        /// 将对象序列化为Xml文件
        /// </summary>
        public static void ToXml<T>(T obj, string fullPath)
        {
            if (File.Exists(fullPath)) File.Delete(fullPath); //存在则删除
            //Step1：文件流——创建xml文件
            FileStream fs = new FileStream(fullPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
            //Step2：写入流
            StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.UTF8);
            //Step3：创建xml序列化器
            XmlSerializer xmlSerializer = new XmlSerializer(obj.GetType());
            //Step4：序列化对象到写入流中
            xmlSerializer.Serialize(sw, obj);
            //Step5：关闭流
            sw.Close();
            fs.Close();
        }
        /// <summary>
        /// 将对象序列化为二进制文件
        /// </summary>
        public static void ToBinary<T>(T obj, string fullPath)
        {
            if (File.Exists(fullPath)) File.Delete(fullPath); //存在则删除
            //Step1：文件流——创建二进制文件
            FileStream fs = new FileStream(fullPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
            //Step2：创建二进制序列化器
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            //Step3：序列化对象到文件流中
            binaryFormatter.Serialize(fs, obj);
            //Step4：关闭流
            fs.Close();
        }
    }
}
